<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>socket</title>
</head>

<body>
    <input type="text" id="msg">
    <input type="button" id="send" value="发送">
    <ul id="receive"></ul>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        const log = console.log.bind(console)
        const socket = io()

        //连接成功时触发
        socket.on('connect', () => {
            console.log('连接成功')
        })

        //连接断开时触发
        socket.on('disconnect', () => {
            console.log('连接断开')
        })

        //收到消息时触发
        socket.on('message', data => {
            var node = document.createElement("li")
            node.innerHTML = "客户端收到 : " + data
            document.querySelector("#receive").appendChild(node)
        })

        document.querySelector("#send").onclick = function() {
            var msg = document.querySelector("#msg").value
            socket.send(msg)
        }
        // socket.on('send', (data) => {
        //     log(data)
        // })
    </script>
</body>

</html>